﻿using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WCS.Entity;
using WCS.Helpers;
using WCS.Helpers.ExportExcel;
using WCS.Utils;

namespace WCS.Controls
{
    public partial class WarehouseInfoIO : UIPage
    {
        public WarehouseInfoIO()
        {
            InitializeComponent();
        }

        public static string connStrings = System.Configuration.ConfigurationManager.AppSettings["SQLConn"].ToString();

        Dictionary<string, string> _MaterialType = new Dictionary<string, string>();
        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SortingTask_Load(object sender, EventArgs e)
        {

            MawbNoBind();
            //WarehourseQuery();
            this.uiPagination1.ActivePage = 1;

        }

        /// <summary>
        /// 数据库对象
        /// </summary>
        static SqlSugarDapper _SqlSugarDapper = SqlSugarDapper.GetDbContext();

        /// <summary>
        /// 主单绑定
        /// </summary>
        private void MawbNoBind()
        {

            //Dictionary<string, string> TaskStateEnum = new Dictionary<string, string>();
            //TaskStateEnum.Add("全部查询", "0");
            //TaskStateEnum.Add("初始创建", "5");
            //TaskStateEnum.Add("等待执行", "25");
            //TaskStateEnum.Add("执行中", "55");

            //TaskState.DataSource = new BindingSource(TaskStateEnum, null);
            //TaskState.DisplayMember = "key";
            //TaskState.ValueMember = "value";

            //TaskState.Text = "全部查询";


            var _material = _SqlSugarDapper.DB.Queryable<PalletToMaterial>().ToList();

            for (int i = 0; i < _material.Count; i++)
            {
                _MaterialType.Add(_material[i].MaterialType, _material[i].MaterialType);

            }

            MaterialTypeComboBox.DataSource = new BindingSource(_MaterialType, null);
            MaterialTypeComboBox.DisplayMember = "key";
            MaterialTypeComboBox.ValueMember = "value";


        }

        /// <summary>
        /// 成绩绑定
        /// </summary>
        private void TaskTableBind()
        {
            //获取当前页面的index
            int index = this.uiPagination1.ActivePage - 1;
            int pageIndex = this.uiPagination1.ActivePage;
            int size = this.uiPagination1.PageSize;
            int begin = (index * size) + 1;
            int end = (index + 1) * size;
            int count = 0;
            //int cMawbNo = (int)this.TaskState.SelectedIndex;
            //this.dgvScoreList.DataSource = "select seqId,createTime,importNo,uldNo,flightNo,etd,mawbNo,pieces,scanPieces,sortedPieces,lightPieces,stackPieces,totalPieces,receiveTime from UldInfo".QueryStrCount(out count);

            //var asd = TaskState.SelectedValue.ToString();
            this.dgvScoreList.DataSource = _SqlSugarDapper.DB.Queryable<WCS.Entity.WarehouseInfo>()
                .OrderBy(w=>w.ID)//然后根据创建时间排序
                .OrderBy(w=>w.index)//然后根据创建时间排序
                .ToPageList(pageIndex, size, ref count);

            //uiPagination1.TotalCount = count;
            this.materialnumber.Text = "0";
        }

        private void WarehourseQuery()
        {
            //获取当前页面的index
            int index = this.uiPagination1.ActivePage - 1;
            int pageIndex = this.uiPagination1.ActivePage;
            int size = this.uiPagination1.PageSize;
            int begin = (index * size) + 1;
            int end = (index + 1) * size;
            int count = 0;
            //int cMawbNo = (int)this.TaskState.SelectedIndex;
            //this.dgvScoreList.DataSource = "select seqId,createTime,importNo,uldNo,flightNo,etd,mawbNo,pieces,scanPieces,sortedPieces,lightPieces,stackPieces,totalPieces,receiveTime from UldInfo".QueryStrCount(out count);

            var palletCode = _SqlSugarDapper.DB.Queryable<PalletToMaterial>()
                .Where(w => w.MaterialType == MaterialTypeComboBox.Text)
                .First().PalletCode;

            int materialNum;
            if (palletCode == "")
            {
                materialNum = _SqlSugarDapper.DB.Queryable<WCS.Entity.WarehouseInfo>()
                .Where(w => w.barCode.Contains("9999999999")).ToList().Count;

                this.dgvScoreList.DataSource = _SqlSugarDapper.DB.Queryable<WCS.Entity.WarehouseInfo>()
                .Where(w => w.barCode.Contains("9999999999"))
                .OrderBy("ID")//然后根据创建时间排序
                .ToPageList(pageIndex, size, ref count);
            }
            else
            {
                materialNum = _SqlSugarDapper.DB.Queryable<WCS.Entity.WarehouseInfo>()
               .Where(w => w.barCode.Contains(palletCode)).ToList().Count;

                this.dgvScoreList.DataSource = _SqlSugarDapper.DB.Queryable<WCS.Entity.WarehouseInfo>()
                .Where(w => w.barCode.Contains(palletCode))
                .OrderBy("ID")//然后根据创建时间排序
                .ToPageList(pageIndex, size, ref count);
            }


            materialnumber.Text = materialNum.ToString();
            //uiPagination1.TotalCount = count;
        }
        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            var Starttime = starttime.Text.Trim();
            var Endtime = endtime.Text.Trim();

            if (MaterialTypeComboBox.Text == "")
            {
                var dataTable = _SqlSugarDapper.DB.Ado.GetDataTable($"Select barCode as '条码',BarCodeData as '物料类型',CreateTime as '入库时间',Task_type as '出入库类型' from WCS_WarehouseIO where CreateTime between '{Starttime}' and '{Endtime}'");

                if (dataTable != null)
                {
                    string path = "";
                    SaveFileDialog saveDialog = new SaveFileDialog();
                    saveDialog.Title = "请选择要导出的位置";
                    saveDialog.Filter = "Excel文件| *.xlsx;*.xls";
                    saveDialog.ShowDialog();
                    path = saveDialog.FileName;
                    if (path.IndexOf(":") < 0) return; //判断是否点击取消

                    ExportToExcel._exportToExcel.DataSetToExcel1(dataTable, path, true);
                }
            }
            else
            {
                var dataTable = _SqlSugarDapper.DB.Ado.GetDataTable($"Select barCode as '条码',BarCodeData as '物料类型',CreateTime as '入库时间',Task_type as '出入库类型' from WCS_WarehouseIO where CreateTime between '{Starttime}' and '{Endtime}'AND BarCodeData='{MaterialTypeComboBox.Text}'");

                if (dataTable != null)
                {
                    string path = "";
                    SaveFileDialog saveDialog = new SaveFileDialog();
                    saveDialog.Title = "请选择要导出的位置";
                    saveDialog.Filter = "Excel文件| *.xlsx;*.xls";
                    saveDialog.ShowDialog();
                    path = saveDialog.FileName;
                    if (path.IndexOf(":") < 0) return; //判断是否点击取消

                    ExportToExcel._exportToExcel.DataSetToExcel1(dataTable, path, true);
                }
            }

        }

        /// <summary>
        /// 快速查询某个时间内的出库入库数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton2_Click(object sender, EventArgs e)
        {
            var Starttime = starttime.Text.Trim();
            var Endtime = endtime.Text.Trim();

            var data = _SqlSugarDapper.DB.Queryable<WarehouseIO>()
                .GroupBy(w => w.Task_type)
                .Where(w => w.CreateTime >= Convert.ToDateTime(Starttime) && w.CreateTime <= Convert.ToDateTime(Endtime))
                .Select(w => new
                {
                    num = SqlFunc.AggregateCount(w.Task_type),
                    type = w.Task_type
                })
                .ToList();
            if (data.Count == 1)
            {
                ShowSuccessDialog($"{Starttime}至{Endtime}出入库数据", $"{data[0].type}-{data[0].num}", UIStyle.Green, false);
            }
            else if (data.Count == 2)
            {
                ShowSuccessDialog($"{Starttime}至{Endtime}出入库数据", $"{data[0].type}-{data[0].num}\r\n{data[1].type}-{data[1].num}", UIStyle.Green, false);
            }
            else
            {
                ShowSuccessDialog($"{Starttime}至{Endtime}出入库数据", $"", UIStyle.Green, false);
            }
        }

        public void ExportDataToExcel(UIDataGridView myDGV)
        {
            string path = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Title = "请选择要导出的位置";
            saveDialog.Filter = "Excel文件| *.xlsx;*.xls";
            saveDialog.ShowDialog();
            path = saveDialog.FileName;
            if (path.IndexOf(":") < 0) return; //判断是否点击取消
            try
            {
                Thread.Sleep(1000);
                StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
                StringBuilder sb = new StringBuilder();
                //写入标题
                for (int k = 0; k < myDGV.Columns.Count; k++)
                {
                    if (myDGV.Columns[k].Visible)//导出可见的标题
                    {
                        //"\t"就等于键盘上的Tab,加个"\t"的意思是: 填充完后进入下一个单元格.
                        sb.Append(myDGV.Columns[k].HeaderText.ToString().Trim() + "\t");
                    }
                }
                sb.Append(Environment.NewLine);//换行
                                               //写入每行数值
                for (int i = 0; i < myDGV.Rows.Count - 1; i++)
                {
                    System.Windows.Forms.Application.DoEvents();
                    for (int j = 0; j < myDGV.Columns.Count; j++)
                    {
                        if (myDGV.Columns[j].Visible)//导出可见的单元格
                        {
                            //注意单元格有一定的字节数量限制,如果超出,就会出现两个单元格的内容是一模一样的.
                            //具体限制是多少字节,没有作深入研究.
                            sb.Append(myDGV.Rows[i].Cells[j].Value.ToString().Trim() + "\t");
                        }
                    }
                    sb.Append(Environment.NewLine); //换行
                }
                sw.Write(sb.ToString());
                sw.Flush();
                sw.Close();
                MessageBox.Show(path + "，导出成功", "系统提示", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFind_Click(object sender, EventArgs e)
        {
            TaskTableBind();
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            TaskTableBind();
        }

        /// <summary>
        /// 页面改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pagingSource"></param>
        /// <param name="pageIndex"></param>
        /// <param name="count"></param>
        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            TaskTableBind();
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            WarehourseQuery();
        }

        private void queryBarCode_Click(object sender, EventArgs e)
        {
            WarehourseQueryBarCode();
        }
        private void WarehourseQueryBarCode()
        {
            //获取当前页面的index
            int index = this.uiPagination1.ActivePage - 1;
            int pageIndex = this.uiPagination1.ActivePage;
            int size = this.uiPagination1.PageSize;
            int begin = (index * size) + 1;
            int end = (index + 1) * size;
            int count = 0;

            var barcode = _SqlSugarDapper.DB.Queryable<WCS.Entity.WarehouseInfo>()
                .Where(w => w.barCode == barcodeTXT.Text)
                .First();

            if (barcode == null)
            {
                this.dgvScoreList.DataSource = _SqlSugarDapper.DB.Queryable<WCS.Entity.WarehouseInfo>()
                .Where(w => w.barCode.Contains("9999999999"))
                .OrderBy("ID")//然后根据创建时间排序
                .ToPageList(pageIndex, size, ref count);
            }
            else
            {
                this.dgvScoreList.DataSource = _SqlSugarDapper.DB.Queryable<WCS.Entity.WarehouseInfo>()
                .Where(w => w.barCode.Contains(barcodeTXT.Text))
                .OrderBy("ID")//然后根据创建时间排序
                .ToPageList(pageIndex, size, ref count);
            }

        }
    }
}
